package com.magic.himalaya;

import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.magic.himalaya.adapters.TrackListAdapter;
import com.magic.himalaya.base.BaseActivity;
import com.magic.himalaya.base.BaseApplication;
import com.magic.himalaya.interfaces.IAlbumDetailVIewCallBack;
import com.magic.himalaya.interfaces.IPlayViewCallBack;
import com.magic.himalaya.presenters.AlbumDetailPresenter;
import com.magic.himalaya.presenters.PlayerPresenter;
import com.magic.himalaya.utils.BlurTransformation;
import com.magic.himalaya.utils.Constants;
import com.magic.himalaya.utils.DisplayUtils;
import com.magic.himalaya.utils.LogUtil;
import com.magic.himalaya.views.LoaderView;
import com.magic.himalaya.views.RoundRectImageView;
import com.squareup.picasso.Picasso;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import java.util.List;

public class DetailActivity extends BaseActivity implements IAlbumDetailVIewCallBack, IPlayViewCallBack {

    private ImageView large_image;  //大背景图
    private RoundRectImageView small_image; //小图标
    private TextView title_text;    //标题
    private TextView announer_text; //作者名
    private AlbumDetailPresenter albumDetailPresenter;  //实现类
    private Album album;
    private int page = 1;//第多少页
    private RecyclerView recyclerView;  //声音展示列表RecyclerView
    private TrackListAdapter trackListAdapter;
    private FrameLayout frameLayout;
    private LoaderView loaderView;
    private PlayerPresenter playerPresenter;
    private View mBtn_player_status;
    private ImageView mImage_player_status;
    private TextView mText_player_status;
    private TwinklingRefreshLayout mRefreshLayout;

    private boolean isLoading = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        //设置系统UI(状态栏隐藏)
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        getWindow().setStatusBarColor(Color.TRANSPARENT);

        //获得专辑详情的逻辑层
        albumDetailPresenter = AlbumDetailPresenter.getInstance();
        //获得播放器的逻辑层
        playerPresenter = PlayerPresenter.getInstance();

        initView(); //初始化所有组件

        initEvent();//初始化事件
        //设置回调函数
        albumDetailPresenter.registerViewCallBack(this);
        playerPresenter.registerViewCallBack(this);
        playerPresenter.isPlaying();//检测是否正在播放中


    }

    private void initEvent() {
        findViewById(R.id.to_back).setOnClickListener(v -> finish());//返回按钮
        //当前播放状态--开始播放|继续播放|暂停播放 的 点击事件
        mBtn_player_status.setOnClickListener(v -> {
            if (playerPresenter != null) {
                //如果播放器列表里面有声音（也许正在播放其它专辑的声音）
                if (playerPresenter.hasPlayerList()) {
                    //如果正在播放就暂停，则播放
                    if (playerPresenter.isPlaying()) {
                        playerPresenter.pause();
                    } else {
                        playerPresenter.play();
                    }
                } else {
                    //否则将播放此专辑的声音从第一个开始播放
                    LogUtil.d("TAG", ":::当前列表没有声音，将此专辑的声音加载进播放器列表");
                    playerPresenter.setMTracks(albumDetailPresenter.getTracks(), 0);
                    playerPresenter.play();
                }
            }
        });


    }

    private void initView() {
        frameLayout = findViewById(R.id.framelayout_content);   //获取列表组件FrameLayout

        //获得专辑数据-----------------------------------渲染页面上的album数据
        album = albumDetailPresenter.getmTargetAlbum();
        //获取页面上方的组件
        large_image = findViewById(R.id.image_large);
        small_image = findViewById(R.id.image_small);
        title_text = findViewById(R.id.text_title);
        announer_text = findViewById(R.id.text_announer);
        //获取当前是否正在被播放组件
        mBtn_player_status = findViewById(R.id.btn_player_status);//当前播放状态
        mImage_player_status = findViewById(R.id.image_player_status);//当前播放状态的图标
        mText_player_status = findViewById(R.id.text_player_status);//当前播放状态的文字


        //上方页面组件渲染,加带蒙板高斯模糊效果
        if (album.getCoverUrlLarge() != null && !album.getCoverUrlLarge().trim().equals(""))
            Picasso.get().load(album.getCoverUrlLarge()).transform(new BlurTransformation(this)).into(large_image);

        if (album.getCoverUrlSmall() != null && !album.getCoverUrlSmall().trim().equals(""))
            Picasso.get().load(album.getCoverUrlSmall()).into(small_image);

        title_text.setText(album.getAlbumTitle());
        announer_text.setText(album.getAnnouncer().getNickname());
        //-----------------------------------------end


        {//设置UILoader加载器，加载网络错误，数据读取，加载中和空数据页面

            if (loaderView == null) {
                loaderView = new LoaderView(this) {
                    @Override
                    public View getSuccessView(ViewGroup container) {
                        return createSuccessView(container);
                    }
                };
                //当网络错误时，重新获取数据
                loaderView.setTrackData(() -> {
                    //获取Track(声音)列表数据
                    albumDetailPresenter.getAlbumDetail(album.getId(), 1);//网络错误时从第一页数据重新获取
                    loaderView.updateStatus(LoaderView.UIStatus.LOADING);
                });
                frameLayout.removeAllViews();
                frameLayout.addView(loaderView);
            }

            //开始初始化请求Track(声音)列表数据，获取第一页数据
            albumDetailPresenter.getAlbumDetail(album.getId(), 1);//请求第一页数据
            loaderView.updateStatus(LoaderView.UIStatus.LOADING);//将当前状态设置为加载中

        }//设置UILoader加载器，加载网络错误，数据读取，加载中和空数据页面_end|||进入此Activity时并开始初始化数据


    }

    /**
     * 只有当 成功获取数据后才会 调用此方法 渲染TrackList（声音）列表数据
     *
     * @param container
     * @return
     */
    private View createSuccessView(ViewGroup container) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_track_list, container, false);
        recyclerView = view.findViewById(R.id.tracks_recyclerview);//获取RecyclerView列表组件
        mRefreshLayout = view.findViewById(R.id.refreshLayout);//获取上下刷新加载框架组件
        initRefreshLayoutListener();//初始化刷新框架事件

        //------------------------- 下方渲染声音Track列表
        //初始化RecyclerView
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setHasFixedSize(true); //设置保持固定大小，这样可优化RecyclerView的性能
        //增加一点装饰线，用于分割每条Item数据
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
                                       @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                DisplayUtils displayUtils = DisplayUtils.getInstance(view.getContext());
                outRect.top = displayUtils.dipToPx(1);
                outRect.bottom = displayUtils.dipToPx(1);
            }

            @Override
            public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }
        });
        //创建RecyclerView适配器
        trackListAdapter = new TrackListAdapter();
        //给适配器设置点击事件
        trackListAdapter.setOnClickCallBack((tracks, position) -> {
            playerPresenter.setMTracks(tracks, position);//设置播放器数据
            //跳转至播放器
            startActivityForResult(new Intent(this, PlayerActivity.class), Constants.REQUEST_CODE);
        });
        recyclerView.setAdapter(trackListAdapter);  //设置适配器
        //------------------------- end
        return view;
    }

    /**
     * 初始化上拉下拉刷新加载的事件
     */
    private void initRefreshLayoutListener() {
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            //上拉刷新
            @Override
            public void onRefresh(final TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                albumDetailPresenter.getAlbumDetail(album.getId(), 1);//请求第一页数据
                loaderView.updateStatus(LoaderView.UIStatus.LOADING);//将当前状态设置为加载中
                mRefreshLayout.finishRefreshing();
            }

            //下拉加载更多
            @Override
            public void onLoadMore(final TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);

                albumDetailPresenter.loadMore(album.getId(), ++page);

                //数据加载完成后调用此方法关闭加载UI
                albumDetailPresenter.setOnTrackListener(str -> {
                    if (str != null) {
                        Toast.makeText(BaseApplication.getsAppContext(), "没有更多数据了", Toast.LENGTH_SHORT).show();
                    }
                    mRefreshLayout.finishLoadmore();
                });

            }
        });
    }


    //===================== 以下为UI回调接口层实现

    /**
     * 将获得的数据设置到适配器中进行数据渲染
     * 数据渲染
     *
     * @param trackList
     */
    @Override
    public void onTrackListLoader(List<Track> trackList) {
        loaderView.updateStatus(LoaderView.UIStatus.SUCCESS);
        trackListAdapter.setData(trackList);
    }

    /**
     * 网络错误时将加载 加载器中的网络错误页面
     */
    @Override
    public void onNetworkError() {
        loaderView.updateStatus(LoaderView.UIStatus.NETWORK_ERROR);
    }

    /**
     * 空数据时将加载 加载器中的空数据页面
     */
    @Override
    public void onTrackEmpty() {
        loaderView.updateStatus(LoaderView.UIStatus.EMPTY);
    }

    /**
     * 加载数据中时 加载加载器中的加载页面
     */
    @Override
    public void onLoading() {
        loaderView.updateStatus(LoaderView.UIStatus.LOADING);
    }

    /**
     * 下拉刷新
     */
    @Override
    public void pullToRefreshMore() {

    }

    /**
     * 加载更多
     */
    @Override
    public void loadMore() {

    }

    //================== 以下为播放器逻辑层的接口回调方法

    @Override
    public void onPlayStart() {
        //当前正在播放中，UI图标设置成暂停图标
        mImage_player_status.setImageResource(R.drawable.selector_press_player_pause_detail);
        mText_player_status.setText("正在播放: " + playerPresenter.getTrack().getTrackTitle());
        mText_player_status.setEllipsize(TextUtils.TruncateAt.MARQUEE);//设置字体滚动效果
        mText_player_status.setHorizontallyScrolling(true);//设置可以水平滚动
        mText_player_status.setMarqueeRepeatLimit(-1);//-1代表无限滚动次数，1是一次
        mText_player_status.setSelected(true);
        mText_player_status.setOnClickListener(v -> //跳转至播放器
                startActivityForResult(new Intent(this, PlayerActivity.class), Constants.REQUEST_CODE));


    }

    @Override
    public void onPlayPause() {
        //当前正暂停播放中，UI图标设置成继续播放图标
        mImage_player_status.setImageResource(R.drawable.selector_press_player_play_detail);
        mText_player_status.setText("继续播放");
        mText_player_status.setEllipsize(TextUtils.TruncateAt.END);//设置字体滚动效果
        mText_player_status.setHorizontallyScrolling(false);//设置可以水平滚动
        mText_player_status.setOnClickListener(null);
    }

    @Override
    public void onPlayStop() {
    }

    @Override
    public void onError() {

    }

    @Override
    public void nextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onNowPlayTime(int time, int duration) {

    }

    @Override
    public void onPlayList(List<Track> trackList) {

    }

    @Override
    public void onListLoaded(List<Track> trackList, int position) {

    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {

    }

    @Override
    public void setViewData(Track track) {

    }

    @Override
    public void onAdLoading() {

    }

    @Override
    public void onAFinished() {

    }

    @Override
    public void toast(String str) {

    }


}